package com.chiry.collectionstream.demos.streams;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Author chiryvan
 * @Date 2022/7/20
 **/
@RestController
public class TestStream {
    //stream map 获取到映射对象值
    //Returns a stream consisting of the results of applying the given function to the elements of this stream.
    @RequestMapping("map")
    public String map(){
        List<User> users = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            User user = new User("username"+i,20+i,"beijing"+i);
            users.add(user);
        }
        List<String> usernames = users.stream().map(User::getUsername).collect(Collectors.toList());
        System.out.println("usernames = " + usernames);
        Set<String> addresses = users.stream().map(User::getAddress).collect(Collectors.toSet());//disorder set
        System.out.println("addresses = " + addresses);
        return usernames.toString();
    }
    @RequestMapping("filter")
    public  String filter(){
        List<String> strings = Arrays.asList("aaa", "bbb", "ccc", "fff");
        Optional<String> first = strings.stream().findFirst();
        if (first.isPresent()){
            String f1 = first.get();
            System.out.println("f1 = " + f1);
        }
        List<String> filterList = strings.stream().filter(s -> "ccc".equals(s)).collect(Collectors.toList());
        System.out.println("filterList = " + filterList);
        return "success";
    }
    @RequestMapping("foreach")
    public String foreach(){
        List<User> users= new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            users.add(new User("xxx" + i, i, "shanghai" + i));
        }
        System.out.println("users = " + users);
        users.stream().forEach(user -> user.setAddress(user.getAddress().replace("shanghai","beijing")));
        System.out.println("users = " + users);
        return "success";
    }
    @RequestMapping("concat")
    public String concat(){
        List<String> strings = Arrays.asList("aaa", "bbb", "ccc", "fff");
        List<String> strings2 = Arrays.asList("ccc", "fff", "ddd", "fff");
        Set<String> collect = Stream.concat(strings.stream(), strings2.stream()).collect(Collectors.toSet());
        System.out.println("collect = " + collect);
        return collect.toString();
    }
}
